import { prisma } from '../../utils/prisma'
import { assertChildOwnership } from '../../utils/guard'
import { z } from 'zod'

const bodySchema = z.object({
  name: z.string().min(1).optional(),
  birthday: z.string().optional(),
  height: z.number().positive().optional(),
  avatarUrl: z.string().optional()
})

export default eventHandler(async (event) => {
  const id = Number(getRouterParam(event, 'id'))
  if (!Number.isFinite(id)) throw createError({ statusCode: 400, statusMessage: 'BAD_ID' })
  await assertChildOwnership(event, id)
  const body = await readBody(event)
  const parsed = bodySchema.safeParse(body)
  if (!parsed.success) throw createError({ statusCode: 422, statusMessage: 'INVALID_INPUT' })
  const { name, birthday, height, avatarUrl } = parsed.data
  const child = await prisma.child.update({
    where: { id },
    data: {
      ...(name !== undefined ? { name } : {}),
      ...(birthday !== undefined ? { birthday: birthday ? new Date(birthday) : null } : {}),
      ...(height !== undefined ? { height } : {}),
      ...(avatarUrl !== undefined ? { avatarUrl } : {})
    }
  })
  return { child }
})


